<?php
/**
 * Created by PhpStorm.
 * User: wei
 * Date: 2016/3/7
 * Time: 22:34
 */
namespace Api\Controller;
use Think\Controller;
use Think\Model;

class ContendController extends BaseController
{
    /***
     * 抢单首页
     */
    public function getOrder(){

        $user_id=I('post.user_id','');
        $key=I('post.key','');
        if($user_id=='' || $key==''){
            $data=array('err_code'=>1003,'err_msg'=>'登录超时');
            $this->ajaxReturn($data,'JSON');
        }

        $userWhere['user_id']=$user_id;
        $userWhere['master_status']=0;
        if(!$user=M('user')->where($userWhere)->select()){
            $data=array('err_code'=>1003,'err_msg'=>'你已被加到黑名单');
            $this->ajaxReturn($data,'JSON');
        }

        $todayTime=getTodayTime();
        $todayLastTime=$todayTime+60*60*24;
        $data=array();
        $data['date']=date('m月d日');
        $data['week']=week();
        $where['worker_user_id']=$user_id;
        //$where['status']=4;
        $where['order_time']=array('between',array($todayTime,$todayLastTime));
        $todayOrder=M('repair_order')->where($where)->select();

        $data['orderCount']=count($todayOrder);
        $money='0.00';
        for($i=0;$i<$data['orderCount'];$i++){
            $money=bcadd($todayOrder[$i]['total'],$money,2);
        }

        if(empty($user[0]['notice_list'])){
            $nwhere['Id']=-1;
        }else{
            $nwhere['Id']=array('in',$user[0]['notice_list']);
        }
        $nwhere['status']=1;
        $data['notice']=M('notice')->where($nwhere)->select();
        foreach($data['notice'] as $k=>$v){
            $data['notice'][$k]['create_time']=date('m月d日 H:i',$data['notice'][$k]['create_time']);
        }
        $owhere['worker_user_id']=$user_id;
        $allCount=M('repair_order')->where($owhere)->count();
        $owhere['status']=10;
        $finishCount=M('repair_order')->where($owhere)->count();
        $data['finish']=($finishCount/$allCount)*100;
        $data['money']=$money;
        $data['is_listen']=$user[0]['is_listen'];
        $data=array('err_code'=>200,'err_msg'=>$data);
        $this->ajaxReturn($data,'JSON');
    }



    /**
     * 开启听单模式
     */
    public function startOrder(){

        $user_id=I('post.user_id',null);
        $action=I('post.action',null);    //0关闭听单 1开启
        $key=I('post.key');
        if(!$user_id){
            $data=array('err_code'=>1001,'err_msg'=>'用户id不能为空');
            $this->ajaxReturn($data,'JSON');
        }

        $modeWhere['user_id']=$user_id;
        $modeWhere['mode_cate']=1;
        $mode=M('user_mode')->where($modeWhere)->limit(1)->select();
        if(empty($mode)){
            $data=array('err_code'=>1003,'err_msg'=>'未配置模式设置');
            $this->ajaxReturn($data,'JSON');
        }

        if($action==1 || $action==0){
            $update['is_listen']=$action;
        }else{
            $data=array('err_code'=>403,'err_msg'=>'action出错');
            $this->ajaxReturn($data,'JSON');
        }

        $where['user_id']=$user_id;
        if(M('user')->where($where)->save($update)===false){
            $data=array('err_code'=>403,'err_msg'=>"false");
            $this->ajaxReturn($data,'JSON');
        }else{
            $data=array('err_code'=>200,'err_msg'=>"true");
            $this->ajaxReturn($data,'JSON');
        }
    }


    /**
     *抢单接口
     */
    public function contendOrder(){
        $master_phone=I('post.phone',null,'int');          //师傅手机
        $master_id=I('post.master_id',null,'int');          //师傅id
        $order_id=I('post.order_id',null);          //对外订单id
        $lng=I('post.lng');     //经度
        $lat=I('post.lat');     //纬度

        if(empty($master_id)){
            $data=array('err_code'=>1002,'err_msg'=>'师傅未选择');
            $this->ajaxReturn($data,'JSON');
        }

        if(empty($order_id)){
            $data=array('err_code'=>1002,'err_msg'=>'订单未选择');
            $this->ajaxReturn($data,'JSON');
        }

        $maswhere['user_id']=$master_id;
        $mas=M('user')->where($maswhere)->find();
        if($mas['master_status']==1 || $mas['master_status']==2){
            $data=array('err_code'=>1002,'err_msg'=>'用户目前不能抢单');
            $this->ajaxReturn($data,'JSON');
        }
        $is_existWhere['r.status']=array('in','-3,2');
        $is_existWhere['r.worker_user_id']=$master_id;
        $is_existWhere['h.count']=0;
        $is_existConut=M('repair_order r')->join('left join zsf_order_status_history h on h.order_id=r.repair_order_id')->where($is_existWhere)->count();
       /* if($is_existConut>=1){
            $data=array(err_code=>2016,err_msg=>'请先完成未抵达订单');
            $this->ajaxReturn($data,'JSON');
        }*/
        //判断此师傅在不在推送列表
        $redis = S(array('type' => 'redis'));
        //$arr=array(1,2,3,4);
        //S(C('REPAIR_ORDER') . '_' . $order_id, $arr);//对应的抢单师傅列表
        //$masterList=S(C('REPAIR_ORDER') . '_' . $order_id);//对应的抢单师傅列表
      //  $is_exist=in_array($master_id,$masterList);
      /*  if(!$is_exist){
            $data=array(code=>1203,msg=>'用户匹配出错');
            $this->ajaxReturn($data,'JSON');
        }*/
        $order_id=M('repair_order')->where("repair_order_num_alias=$order_id")->find();

        //检查订单是否已被抢
        $date=date('H:i:s');
        $key=C('REPAIR_ORDER') . '_key_' . $order_id['repair_order_id'];
        $checkOrder=S($key);

        $abc=var_export($checkOrder,true);
        file_put_contents("/tmp/log.txt","抢单接口:{$date}----{$key}===={$abc}\r\n",FILE_APPEND);
      // echo  $checkOrder;exit;
        if($abc==0){
            $status['status']=-1;
            $w['repair_order_num_alias']=$order_id['repair_order_num_alias'];
            M('repair_order')->where($w)->save($status);
            $status['status']=3;
            $pw['order_id']=$order_id['repair_order_id'];
            M('pushorder')->where($pw)->save($status);
            $data=array('err_code'=>1204,'err_msg'=>'订单已被其他师傅接单');
            $this->ajaxReturn($data,'JSON');
        }elseif(empty($checkOrder) || $abc==2){
            $data=array('err_code'=>1205,'err_msg'=>'订单已取消');
            $this->ajaxReturn($data,'JSON');
        }else{
            S($key,0);
            $key1=S($key);
            file_put_contents("/tmp/log.txt","更改redis:{$date}===={$key1}\r\n",FILE_APPEND);
        }


        $orderWhere['repair_order_num_alias']=$order_id['repair_order_num_alias'];
        if(!$o_id=M('repair_order')->where($orderWhere)->select()){
            $sql=M('repair_order')->where($orderWhere)->select(false);
            file_put_contents("/tmp/log.txt","Comtend/contendOrder:-------订单号出错{$sql}");
            $data=array('err_code'=>1002,'err_msg'=>'订单号出错');
            $this->ajaxReturn($data,'JSON');
        }

        $order_id=$order_id['repair_order_num_alias'];
        $order=M('repair_order');
        $where['repair_order_num_alias']=$order_id;
        $orderData['worker_user_id']=$master_id;
        $orderData['worker_tel']=$master_phone;
        $orderData['order_time']=time();
        if($order->where($where)->save($orderData)===false){
            $data=array('err_code'=>403,'err_msg'=>'发生未知错误');
            $this->ajaxReturn($data,'JSON');
        }else{
            //开启事务
            $history=M('order_status_history');
            $history->startTrans();
            //修改订单状态
            $order_status['order_id']=$o_id[0]['repair_order_id'];
            $order_status['status']=2;
            $order_status['order_type']=1;
            $order_status['add_time']=time();
            $history->add($order_status);

            //更改经纬度
            updateLngLat($master_phone,$lng,$lat);


            $orderSave['status']=2;
            $o_Save=M('repair_order')->where("repair_order_id=".$o_id[0]['repair_order_id'])->save($orderSave);

            //修改订单
            $where['order_id']=$o_id[0]['repair_order_id'];
            $map['status']=1;
            $pushorder=M('pushorder');
            $push=$pushorder->where($where)->save($map);
            if($history && $push && $o_Save){
                $history->commit();
            }else{
                $history->rollback();
                S($key,1);
                $data=array('err_code'=>403,'err_msg'=>'发生回滚错误');
                $this->ajaxReturn($data,'JSON');
            }

            //jpush推送
           /* $model=M();
            $sql="select ro.worker_tel,u.phone,ro.repair_order_num_alias from zsf_repair_order ro left join zsf_user u on ro.user_id=u.user_id where ro.repair_order_num_alias=".$order_id;
            $alias=$model->query($sql);
            if($alias){
                file_put_contents('/tmp/log.txt',"进入极光",FILE_APPEND);
                $number=substr($alias[0]['worker_tel'],-4);
                jpushStr($alias[0]['phone'],'尾号为'.$number.'抢单成功！订单号为：'.$alias[0]['repair_order_num_alias']);
                file_put_contents('/tmp/log.txt',"别名：{$number}-----订单号：".$alias[0]['repair_order_num_alias']."\r\n",FILE_APPEND);
            }*/
            $order=array('order_id'=>$order_id);
            $data=array('err_code'=>200,'err_msg'=>$order);
            $this->ajaxReturn($data,'JSON');
        }

    }




    //师傅端轮询接口
    public function masterOrder(){

        $user_id=I('post.user_id','','int');
        $where['user_id']=$user_id;
        $type=I('post.type','','int');
        $key=I('post.key','','int');
        $valid_time=time()-60*60*24;


        $orderList=array();
        $master=M('user')->where("user_id=$user_id")->field('lng,lat,identity')->find();
        if($type!=$master['identity'] || $type!=2){
            $data=array('err_code'=>1201,'err_msg'=>'当前身份不是师傅');
            $this->ajaxReturn($data,'JSON');
        }

        if($master['master_status']==1){
            $data=array('err_code'=>1002,'err_msg'=>'用户目前不能抢单');
            $this->ajaxReturn($data,'JSON');
        }
        $Model = M();
        //超过24小时订单自动取消
        $updatesql="update zsf_repair_order ro left join zsf_pushorder po on ro.repair_order_id=po.order_id set ro.status=-1,po.status=2 where ro.set_time<$valid_time and ro.status=1";

        M()->execute($updatesql);
      /*  $umwhere['mode_cate']=1;
        $umwhere['user_id']=$user_id;
        $mode=M('user_mode')->where($umwhere)->find();*/
        $ucwhere['user_id']=$user_id;
        $uc=M('user_repair_conf')->where($ucwhere)->select();
        $ucwhere['is_good']=1;
        $uc2=M('user_repair_conf')->field('category_id')->where($ucwhere)->select();
        //$ucwhere['is_good']=0;
        //$uc3=M('user_repair_conf')->field('category_id')->where($ucwhere)->select();
        $uc2str='';
        $ucstr='';
        $uc3str='';

        foreach($uc as $uck=>$ucv){
            $ucstr.=$ucv['category_id'].',';
            if($ucv['is_good']==0){
                $uc3str.=$ucv['category_id'].',';
            }
        }
        foreach($uc2 as $uc2k=>$uc2v){
            $uc2str.=$uc2v['category_id'].',';
        }

        $ucstr=trim($ucstr,',');    //可以抢单的分类id
        $uc2str=trim($uc2str,',');  //专长的分类id
        $uc3str=trim($uc3str,',');  //普通的分类id

     //   $sql="select r.user_id,r.lng,r.lat,r.fault_type,r.repair_order_num_alias,r.book_time,r.order_type,r.mode_charging,r.city,r.shipping_addr,r.repair_order_id,c.category_name,(r.total-r.diagnosis_cost) total,r.fault_id_list,r.tip from zsf_pushorder po left join zsf_repair_order r  on po.order_id=r.repair_order_id left join zsf_category c on r.category_id=c.category_id where po.user_id={$user_id} and po.status=0 order by po.Id desc";
     //   var_dump($sql);exit;
        $thiwhere['po.user_id']=$user_id;
        $thiwhere['po.status']=0;
        $thiwhere['r.category_id']=array('in',$ucstr);
        $orders= M('pushorder po')
            ->join('left join zsf_repair_order r on po.order_id=r.repair_order_id ')
            ->join('left join zsf_category c on r.category_id=c.category_id ')
            ->field('r.category_id,r.user_id,r.lng,r.lat,r.fault_type,r.repair_order_num_alias,r.book_time,r.order_type,r.mode_charging,r.city,r.shipping_addr,r.repair_order_id,c.category_name,(r.total-r.diagnosis_cost) total,r.fault_id_list,r.tip')
            ->where($thiwhere)
            ->order('po.Id desc')
            ->select();

     //   $orders=$Model->query($sql);
        if(empty($orders)){
            $data=array('err_code'=>200,'err_msg'=>array());
            $this->ajaxReturn($data,'JSON');
        }
        $repairWhere['user_id']=$user_id;
        $repairWhere['mode_cate']=1;
        $mode=M('user_mode')->field('mode_order,mode_charging')->where($repairWhere)->find();
       // file_put_contents("/tmp/test.txt","mode:".var_export($mode,true)."----",FILE_APPEND);
        foreach($orders as $k=>$v){
            //判断是否配置专修抢单模式
            $fl=in_array($v['mode_charging'],explode(',',$mode['mode_charging']));
            if(!$fl){
                unset($orders[$k]);
                continue;
            }

            $fl=in_array($v['order_type'],explode(',',$mode['mode_order']));
            if(!$fl){
                unset($orders[$k]);
                continue;
            }

            //判断是否配置该专修
            if($v['mode_charging']==3){
                $fl=in_array($v['category_id'],explode(',',$uc2str));
                if(!$fl){
                    //没配置，删除该订单
                    unset($orders[$k]);
                    continue;
                }
            }

            if($v['mode_charging']==1 || $v['mode_charging']==2){
                $flv=in_array($v['category_id'],explode(',',$uc3str));
                if(!$flv){
                    //没配置，删除该订单
                    unset($orders[$k]);
                    continue;
                }
            }
            if(!empty($v['fault_id_list'])){
                //获取故障名称
                $failutWhere['fault_id']=array('in',$v['fault_id_list']);
                $faultArr=M('fault')->where($failutWhere)->field('name,fault_type')->select();
                if(!empty($faultArr)){
                    $pic=array();
                    $faultStr='';
                    foreach($faultArr as $key=>$value){
                        $faultStr.=$value['name'].';';
                        array_push($pic,$value['fault_type']);
                    }
                    if(in_array(2,$pic)){
                        $v['total']=0;
                    }
                    if($v['book_time']) {
                        $v['book_time'] = date('Y-m-d H:i:s', $v['book_time']);
                    }
                    $v['fault_list']=$faultStr;
                    $v['distance']=getDistance($master['lat'],$master['lng'],$v['lat'],$v['lng']);
                    array_push($orderList,$v);
                }
            }



        }
        if(count($orderList)>0){
            $data=array('err_code'=>200,'err_msg'=>$orderList);
            $this->ajaxReturn($data,'JSON');
        }else{
            $data=array('err_code'=>200,'err_msg'=>array());
            $this->ajaxReturn($data,'JSON');
        }
    }



    /**
     * 订单详情页
     */

    public function orderDetail(){
        //\Think\Log::write(time(),'WARN');
        //$kaishi=time();
        $master_id=I('post.user_id','','int');
        $order_id=I('post.order_id');
        $type=I('post.type');     //1业主 2师傅
        if(empty($master_id)){
            $data=array('err_code'=>1002,'err_msg'=>'缺少师傅');
            $this->ajaxReturn($data,'JSON');
        }

    /*    if($type==1){
            $where['ro.user_id']=$master_id;
            $id='ro.user_id';
        }else{
            $where['ro.worker_user_id']=$master_id;
            $id='ro.worker_user_id';
        }*/

        $where['ro.repair_order_num_alias']=$order_id;

        $detail=M('repair_order ro')
            ->join('left join zsf_user_real_info info on ro.worker_user_id=info.user_id')
            ->join("left join zsf_user u on ro.worker_user_id=u.user_id")
            ->join("left join zsf_user u2 on ro.user_id=u2.user_id")
            ->where($where)
            ->field('ro.category_id,ro.tip,ro.fixed_price,info.grade,u.user_face master_face,u2.user_face,ro.shipping_name user_name,ro.lng lng2,ro.lat lat2,u.lng lng1,u.lat lat1,
            info.id_name master_name,ro.protocol_id,ro.repair_order_id,(ro.total-ro.diagnosis_cost) total,ro.shipping_name,ro.category_id,ro.diagnosis_cost,ro.repair_order_num_alias
            ,ro.user_id,ro.shipping_tel,ro.user_comment,ro.master_comment,ro.shipping_addr,ro.mode_charging
            ,ro.worker_user_id,ro.volume_list_id,ro.worker_tel,ro.order_type,ro.book_time,ro.status,ro.category_name,ro.amount_paid,ro.update_cnt,ro.is_complaint,ro.doorplate,ro.is_refund,ro.is_apply')
            ->find();


        foreach($detail as $k=>$v){
            if($detail[$k]==null){
                $detail[$k] ='';
            }
        }

        if(empty($detail)){
            $data=array('err_code'=>1008,'err_msg'=>'订单不存在');
            $this->ajaxReturn($data,'JSON');
        }
        $isCancel=$this->orderisCancel($detail['repair_order_id']);
      /*  if(!$isCancel){
            $data=array('err_code'=>1234,err_msg=>'订单已取消');
            $this->ajaxReturn($data,'JSON');
        }*/

        $detailWhere['repair_order_id']=$detail['repair_order_id'];
        $detailWhere['status']=array('in','0,1,2,3');
        $fault=M('repair_order_detail')->where($detailWhere)->field('status,fault_type,repair_order_id,fault_id,price,material_cost,deplete_cost,artificial_cost,fault_name')->order('status desc')->select();
        $sta=$fault[0]['status'];
        $detail['fault_list']=array();
        foreach($fault as $k1=>$v1){
              if($v1['status']==$sta){
                  array_push($detail['fault_list'],$v1);
              }
        }
        $awhere['category_id']=$detail['category_id'];
        $agreement=M('agreement')->where($awhere)->field('id,unit,count,category_id,assure_percentage,percentage')->select();
        //$sqltime=time();
       // \Think\Log::write('查询数据库所用时间:'.$kaishi-$sqltime,'WARN');
        foreach($agreement as $k=>$v){
            $agreement[$k]['bond']=bcmul($detail['total'],$agreement[$k]['assure_percentage']/100,2);   //保证金
            $agreement[$k]['maintain']=bcmul($detail['total'],$agreement[$k]['percentage']/100,2);    //维修金
        }
        //查询支付协议
        $pwhere['order_id']=$detail['repair_order_num_alias'];
        $pwhere['status']=array('in','0,1,2,3');
        $detail['protocol']=M('repair_order_protocol')->where($pwhere)->order('status desc')->find();

        //获取距离
        $detail['distance']=getDistance($detail['lat1'],$detail['lng1'],$detail['lat2'],$detail['lng2']);

        //获取可用电子券数
        if($detail['fixed_price']==0.00){
            $vwhereMin=$detail['total'];
        }else{
            $vwhereMin=$detail['fixed_price'];
        }
        $vwhere['user_id']=$detail['user_id'];
        $vwhere['start_time']=array('lt',time());
        $vwhere['end_time']=array('gt',time());
        $vwhere['min']=array('lt',$vwhereMin);
        $vwhere['status']=1;
        $vol=M('volume_list')->where($vwhere)->select();

        $detail['volume']=0;
        foreach($vol as $vlk=>$vlv){
            $abcd=explode('|',$vlv['category_id']);
            if(in_array($detail['category_id'],$abcd)){
                $detail['volume']++;
            }
        }


        //获取已使用电子券
        if($detail['volume_list_id']){
            $vowhere['volume_list_id']=empty($detail['volume_list_id'])?'':$detail['volume_list_id'];
            $detail['in_volume']=M('volume_list')->where($vowhere)->field('volume_list_id,total')->find();
        }else{
            $detail['in_volume']=new \stdClass();
        }

        //获取当前订单状态
        if($type==1){
            $swhere['h.order_id']=$detail['repair_order_id'];
            if($detail['status']=='-1'){
                $cancelResult = M('repair_order_cancel')->field('user_id')->where("order_id = ".$detail['repair_order_id'])->find();
                if($detail['user_id'] == $cancelResult['user_id']){
                    $swhere['s.user_type']=1;
                }elseif ($detail['worker_user_id'] == $cancelResult['user_id']){
                    $swhere['s.user_type']=2;
                }
            }else{
                $swhere['s.user_type']=1;
            }
            $status=M('order_status_history h')->join('zsf_config_status s on s.status=h.status')
                ->where($swhere)
                ->order('h.add_time desc')
                ->find();

            if($status['count']>0){
                $detail['order_status']=$status['content1'];
            }else{
                $detail['order_status']=$status['content'];
            }

            $detail['order_status_name']=$status['name'];
            if($status['status']==1 || $status['status']==2 ||$status['status']==-3){
                $detail['order_status_type']='待服务';
            }elseif($status['status']==-1 || $status['status']==10){
                $detail['order_status_type']='已完成';
            }elseif($status['status']==8 || $status['status']==9){
                $detail['order_status_type']='维保中';
            }else{
                $detail['order_status_type']='服务中';
            }
            $detail['order_status_time']=date('Y-m-d H:i:s',$status['add_time']);
        }else{
            $swhere['h.order_id']=$detail['repair_order_id'];
            if($detail['volume_list_id']){
                $volResult = M('volume_list')->field('total')->where("volume_list_id = $detail[volume_list_id] and status = 2")->find();
                $detail['amount_paid'] += $volResult['total'];
            }
            if($detail['status']=='-1'){
                $cancelResult = M('repair_order_cancel')->field('user_id')->where("order_id = ".$detail['repair_order_id'])->find();
                if($detail['user_id'] == $cancelResult['user_id']){
                    $swhere['s.user_type']=1;
                }elseif ($detail['worker_user_id'] == $cancelResult['user_id']){
                    $swhere['s.user_type']=2;
                }
            }else {
                $swhere['s.user_type'] = 2;
            }
            $status=M('order_status_history h')->join('zsf_config_status s on s.status=h.status')
                ->where($swhere)
                ->order('h.add_time desc')
                ->find();

            if($status['count']>0){
                $detail['order_status']=$status['content1'];
            }else{
                $detail['order_status']=$status['content'];
            }

            $detail['order_status_name']=$status['name'];
            if($status['status']==1 || $status['status']==2 ||$status['status']==-3){
                $detail['order_status_type']='待服务';
            }elseif($status['status']==-1 || $status['status']==10){
                $detail['order_status_type']='已完成';
            }elseif($status['status']==8 || $status['status']==9){
                $detail['order_status_type']='维保中';
            }else{
                $detail['order_status_type']='服务中';
            }
            $detail['order_status_time']=date('Y-m-d H:i:s',$status['add_time']);
        }

        //$fortime=time();
       // unset($detail['lng2']);
       // unset($detail['lat2']);
      //  unset($detail['lng1']);
      //  unset($detail['lat1']);
        if($detail['book_time']){
            $detail['book_time']=date('Y-m-d H:i:s',$detail['book_time']);
        }
        //\Think\Log::write('foreache所用时间:'.$sqltime-$fortime,'WARN');
        $detail['agreement']=$agreement;
        $data=array('err_code'=>200,'err_msg'=>$detail);
        $this->ajaxReturn($data,'JSON');
    }





    /**
     * 取消抢单接口
     */
    public function cancelOrder(){

        $user_id=I('post.user_id');
        $order_id=I('post.order_id');
        if(empty($user_id)){
            $data=array('err_code'=>1002,'err_msg'=>'缺少师傅id');
            $this->ajaxReturn($data,'JSON');
        }

        if(empty($order_id)){
            $data=array('err_code'=>1003,'err_msg'=>'缺少订单id');
            $this->ajaxReturn($data,'JSON');
        }

        $o_id=M('repair_order')->where("repair_order_num_alias=$order_id")->field('repair_order_id')->limit(1)->select();

        $where['order_id']=$o_id[0]['repair_order_id'];
        $where['user_id'] = $user_id;
        $save['status']=3;
        $update_order=M('pushorder')->where($where)->save($save);
         if($update_order===false){
             $data=array('err_code'=>403,'err_msg'=>'订单号不存在');
             $this->ajaxReturn($data,'JSON');
         }else{
             $data=array('err_code'=>200,'err_msg'=>true);
             $this->ajaxReturn($data,'JSON');
         }
    }





    /**
     * 支付协议接口
     */
    public function pay(){

        $agreement_id=I('post.agreement_id');               //支付协议id
        $order_id=I('post.order_id');                       //订单id
        $user_id=I('post.user_id');                       //用户id
        $fixed_price=I('post.fixed_price',NULL);                //一口价



        if(empty($agreement_id)){
            $data=array('err_code'=>1002,'err_msg'=>'缺少支付协议id');
            $this->ajaxReturn($data,'JSON');
        }

        if(empty($user_id)){
            $data=array('err_code'=>1003,'err_msg'=>'缺少用户id');
            $this->ajaxReturn($data,'JSON');
        }

        if(empty($order_id)){
            $data=array('err_code'=>1003,'err_msg'=>'缺少订单id');
            $this->ajaxReturn($data,'JSON');
        }


        $awhere['id']=$agreement_id;
        $agreement=M('agreement')->where($awhere)->limit(1)->select();

        $reorder['repair_order_num_alias']=$order_id;

        $o_id=M('repair_order')->where($reorder)->select();

        $isCancel=$this->orderisCancel($o_id[0]['repair_order_id']);

        if(!$isCancel){
            $data=array('err_code'=>1234,'err_msg'=>'订单已取消');
            $this->ajaxReturn($data,'JSON');
        }

        //查找是否有业主不同意的故障 修改为0
        $detaiOrderid['repair_order_id'] = array('eq',$o_id[0]['repair_order_id']);
        $detaiOrderid['status'] = array('eq',3);
        $detailResult = M('repair_order_detail')->where($detaiOrderid)->select();
        if($detailResult){
            $updata['status'] = 0;
            M('repair_order_detail')->where($detaiOrderid)->save($updata);
        }

        $fWhere['fault_id']=array('in',$o_id[0]['fault_id_list']);
        $fWhere['type']=$o_id[0]['mode_charging'];
        $fcost=M('fault_cost')->where($fWhere)->select();       //故障总价
        $total='';
        foreach($fcost as $k1=>$v1){
            $total=bcadd($total,$v1['material_cost'],2);
            $total=bcadd($total,$v1['deplete_cost'],2);
            $total=bcadd($total,$v1['artificial_cost'],2);
        }

        if(empty($fixed_price)){
//            $total=bcadd($total,$o_id[0]['diagnosis_cost']);               //总额  诊断费+故障费
//            $total=bcadd($total,$o_id[0]['tip']);                            //总额  +小费
            $bond=bcmul($total,$agreement[0]['assure_percentage']/100,3);              //保证金
            $maintain=bcmul($total,$agreement[0]['percentage']/100,3);          //维修金
        }else{
//            $total=$fixed_price;
            $bond=bcmul($fixed_price,$agreement[0]['assure_percentage']/100,3);              //保证金
            $maintain=bcmul($fixed_price,$agreement[0]['percentage']/100,3);          //维修金
//            $thwh['repair_order_num_alias']=$o_id[0]['repair_order_num_alias'];
//            $saas['fixed_price']=$total;
//            M('repair_order')->where($thwh)->save($saas);
        }

        $protocol['gold']=$o_id[0]['total'];
        $protocol['fixed_price']= $fixed_price;
        $protocol['maintain']=$maintain;
        $protocol['gold_ratio']=$agreement[0]['percentage'];
        $protocol['bond']=$bond;
        $protocol['bond_ratio']=$agreement[0]['assure_percentage'];
        $protocol['add_time']=time();
        $protocol['status']=1;
        $protocol['agreement_id'] = $agreement_id;
        $protocol['user_id']=$user_id;
        $protocol['count']=$agreement[0]['count'];
        $protocol['unit']=$agreement[0]['unit'];
        $protocol['order_id']=$o_id[0]['repair_order_num_alias'];
        $protocol['donetime']=time();
        $protocolOrder=M('repair_order_protocol');


        if($pro_id=$protocolOrder->where("order_id=".$o_id[0]['repair_order_num_alias'])->find()){
           $protocolOrder->where("order_id=".$o_id[0]['repair_order_num_alias'])->save($protocol);
            $pro_id=$pro_id['protocol_id'];
        }else{
            $pro_id=M('repair_order_protocol')->add($protocol);
            if($pro_id===false){
                $data=array('err_code'=>403,'err_msg'=>false);
                $this->ajaxReturn($data,'JSON');
            }

        }

        //更改订单状态
        $order_status['order_id']=$o_id[0]['repair_order_id'];
        $order_status['status']=4;
        $order_status['order_type']=1;
        $order_status['add_time']=time();
        M('order_status_history')->add($order_status);

        //更新订单协议id
        $w['repair_order_id'] = $o_id[0]['repair_order_id'];

        $repair_order['status'] = '4';
        //$repair_order['protocol_id'] = $pro_id;
        M('repair_order')->where($w)->save($repair_order);
        $data=array('err_code'=>200,'err_msg'=>true);
        $this->ajaxReturn($data,'JSON');

    }



    /**
     * 修改订单
     */
    public function faultDetail(){

        $order_id=I('post.order_id');
        $user_id=I('post.user_id','','int');

        if(empty($user_id)){
            $data=array('err_code'=>1002,'err_msg'=>'用户id不能为空');
            $this->ajaxReturn($data,'JSON');
        }

        if(empty($order_id)){
            $data=array('err_code'=>1003,'err_msg'=>'订单id不能为空');
            $this->ajaxReturn($data,'JSON');
        }


        $order=M('repair_order')->where("repair_order_num_alias=$order_id and worker_user_id=$user_id")->limit(1)->select();

        if(empty($order)){
            $data=array('err_code'=>1003,'err_msg'=>'订单不存在');
            $this->ajaxReturn($data,'JSON');
        }

        $isCancel=$this->orderisCancel($order[0]['repair_order_id']);
        if(!$isCancel){
            $data=array('err_code'=>1234,'err_msg'=>'订单已取消');
            $this->ajaxReturn($data,'JSON');
        }

        $originalWhere['repair_order_id']=$order[0]['repair_order_id'];
        $original_fault=M('repair_order_detail')->where($originalWhere)->select();

        $sql="select * from zsf_fault f left join zsf_fault_cost fc on f.fault_id=fc.fault_id where fc.type=".$order[0]['mode_charging']." and f.category_id=".$order[0]['category_id'];
       // $fault=M('fault')->where("category_id=".$order[0]['category_id'])->select();

        $fault=M()->query($sql);
        $data=array('err_code'=>200,fault=>$fault,original=>$original_fault);
        $this->ajaxReturn($data,'JSON');
    }




    //故障价钱
    public function fault_cost(){

        $faultIds=I('post.fault');
        $order_id=I('post.order_id');
        $user_id=I('post.user_id');
        $agreement_id=I('post.agreement_id');

        if(empty($faultIds)){
            $data=array('err_code'=>1003,'err_msg'=>'故障不能为空');
            $this->ajaxReturn($data,'JSON');
        }

        if(empty($order_id)){
            $data=array('err_code'=>1003,'err_msg'=>'订单id不能为空');
            $this->ajaxReturn($data,'JSON');
        }

        if(empty($user_id)){
            $data=array('err_code'=>1003,'err_msg'=>'用户id不能为空');
            $this->ajaxReturn($data,'JSON');
        }

        if(empty($agreement_id)){
            $data=array('err_code'=>1003,'err_msg'=>'支付协议id不能为空');
            $this->ajaxReturn($data,'JSON');
        }

        //查询上门方式
        $oWhere['repair_order_num_alias']=$order_id;
        $oWhere['worker_user_id']=$user_id;
        $mode_charging=M('repair_order')->where($oWhere)->field('mode_charging')->select();

        //查询故障价格
        $fWhere['fault_id']=array('in',$faultIds);
        $fWhere['type']=$mode_charging[0]['mode_charging'];
        $fault_cost=M('fault_cost')->where($fWhere)->select();

        if(empty($fault_cost)){
            $data=array('err_code'=>1005,'err_msg'=>'故障价格出错');
            $this->ajaxReturn($data,'JSON');
        }

        //计算故障总价
        $sum='0';
        foreach($fault_cost as $k1=>$v1){
            $sum=bcadd($sum,$v1['material_cost'], 2);
            $sum=bcadd($sum,$v1['deplete_cost'], 2);
            $sum=bcadd($sum,$v1['artificial_cost'], 2);
        }

        //计算比例
        $aWhere['Id']=$agreement_id;
        $agreement=M('agreement')->where($aWhere)->limit(1)->select();

        if(empty($agreement)){
            $data=array('err_code'=>1004,'err_msg'=>'支付协议出错');
            $this->ajaxReturn($data,'JSON');
        }

        $data['guarantee']=bcmul($sum,$agreement[0]['assure_percentage']/100, 2);   //保证金
        $data['service']=bcmul($sum,$agreement[0]['percentage']/100, 2);            //维修金

        $data=array('err_code'=>200,'err_msg'=>$data);
        $this->ajaxReturn($data,'JSON');
    }




    /**
     * 师傅轮询修改订单是否同意
     */
    public function agreeChange(){
        $order_id=I('post.order_id');
        $master_id=I('post.user_id');

        if(empty($order_id)){
            $data=array('err_code'=>1003,'err_msg'=>'缺少订单id');
            $this->ajaxReturn($data,'JSON');
        }

        if(empty($master_id)){
            $data=array('err_code'=>1003,'err_msg'=>'缺少用户id');
            $this->ajaxReturn($data,'JSON');
        }

        //查询订单是否存在
        $oWhere['repair_order_num_alias']=$order_id;
        $oWhere['worker_user_id']=$master_id;
        $order=M('repair_order')->where($oWhere)->limit(1)->select();
        if(empty($order)){
            $data=array('err_code'=>1004,'err_msg'=>'订单不存在');
            $this->ajaxReturn($data,'JSON');
        }

        $isCancel=$this->orderisCancel($order[0]['repair_order_id']);
        if(!$isCancel){
            $data=array('err_code'=>1234,'err_msg'=>'订单已取消');
            $this->ajaxReturn($data,'JSON');
        }

        $dWhere['repair_order_id']=$order[0]['repair_order_id'];
        $dflag=0;
        $pflag=0;
        $dorder=M('repair_order_detail')->where($dWhere)->select();

        if(empty($dorder)) {
            $data = array('err_code' => 1101, 'err_msg' => '不存在');
            $this->ajaxReturn($data, 'JSON');

        }
        foreach($dorder as $d=>$dv){
            switch($dv['status']){
                case 2:
                    $dflag=2;
                    break;break;
                case 3:
                    $dflag=3;
                    $dWhere['status']=3;
                    $mapDe['status']=4;
                    $dorder=M('repair_order_detail')->where($dWhere)->save($mapDe);
                    break;break;
            }
        }

        $pWhere['order_id']=$order[0]['repair_order_id'];
        $porder=M('repair_order_protocol')->where($pWhere)->select();
        foreach($porder as $p=>$pv){
            switch($pv['status']){
                case 2:
                    $pflag=2;
                    break;break;
                case 3:
                    $pflag=3;
                    $pWhere['status']=3;
                    $mapPro['status']=4;
                    M('repair_order_protocol')->where($pWhere)->save($mapPro);
                    break;break;
            }
        }

         //$dflag==2 && $pflag==2 业主同意
        if($dflag==2 && $pflag==2){
            //修改订单状态  0变4 2变0
            $detail=M('repair_order_detail');
           // M('repair_order_protocol')->;
            $detail->startTrans();
            $dcWhere['repair_order_id']=$order[0]['repair_order_id'];
            $dcWhere['status']=0;
            $change0_4=true;
            $change2_0=true;
            $changep0_4=true;
            $changgep2_0=true;
            $changDetail=$detail->where($dcWhere)->select();
            if(!empty($changDetail)){
                //把旧有的订单故障状态改为丢弃的
                $changeD['status']=4;
                $change0_4=$detail->where($dcWhere)->save($changeD);
            }
            //把新修改的订单故障修改为正常状态的

            $dcWhere['status']=2;
            $change2=$detail->where($dcWhere)->select();
            if(!empty($change2)){
                $changeD['status']=0;
                $change2_0=$detail->where($dcWhere)->save($changeD);
            }

            //修改订单支付协议状态 0变4 2变0
            $pcWhere['order_id']=$order[0]['repair_order_id'];
            $pcWhere['status']=0;
            $changeP['status']=4;
            $changep=M('repair_order_protocol')->where($pcWhere)->select();
            if(!empty($changep)){
                $changep0_4=M('repair_order_protocol')->where($pcWhere)->save($changeP);

            }

            $pcWhere['status']=2;
            $changeP['status']=0;
            $changgep2=M('repair_order_protocol')->where($pcWhere)->select();
            if(!empty($changgep2)){
                $changgep2_0=M('repair_order_protocol')->where($pcWhere)->save($changeP);
            }

            if($change0_4 && $change2_0 && $changep0_4 && $changgep2_0){
                $detail->commit();
            }else{
                $detail->rollback();
                $data=array(code=>1113,msg=>'发生回滚错误');
                $this->ajaxReturn($data,'JSON');
            }

            //更新订单总金额
            $sum=M('repair_order_detail')->where("repair_order_id=".$order[0]['repair_order_id'])->field('sum(price) sum')->find();
           $data['fault_money']=$sum['sum'];                       //故障总额

            M('repair_order')->where("repair_order_id=".$order[0]['repair_order_id'])->save($data);
            if($order[0]['volume_list_id']){
                $volume=M('zsf_volume_list')->where("volume_list_id=".$order[0]['volume_list_id'])->field('total')->find();
                $sum=bcsub($sum['sum'],$volume['total']);
            }
            //M('repair_order')->where("repair_order_id=".$order[0]['repair_order_id'])->setInc('total',3);
            $sql="update zsf_repair_order set total=tip+diagnosis_cost+".$sum['sum']." where repair_order_id=".$order[0]['repair_order_id'];
            M()->execute($sql);

            $data=array('err_code'=>200,'err_msg'=>'同意');
            $this->ajaxReturn($data,'JSON');
        }elseif($dflag==3 || $pflag==3){
            $data=array('err_code'=>1006,'err_msg'=>'不同意');
            $this->ajaxReturn($data,'JSON');
        }else{
            $data=array('err_code'=>1007,'err_msg'=>'oooooo');
            $this->ajaxReturn($data,'JSON');
        }
    }



    /**
     * 查询订单是否被取消
     */
    private function orderisCancel($order_id){
        $order=M('repair_order')->where("repair_order_id=$order_id")->find();
        if($order['status']==-1){
            return false;
        }else{
            return true;
        }
    }


    //查询经纬度附近师傅
    public function nearby(){
        $lng=I('post.lng');         //经度
        $lat=I('post.lat');          //纬度
        $scope=I('post.scope','2','int');     //搜索范围
        if(empty($lng) || empty($lat)){
            $data=array('err_code'=>403,'err_msg'=>'经纬度不能为空');
            $this->ajaxReturn($data,'JSON');
        }

        $sql="select lng,lat from zsf_user where sqrt(
    (((%f-lng)*PI()*12656*cos(((%f+lat)/2)*PI()/180)/180)
    *((%f-lng)*PI()*12656*cos (((%f+lat)/2)*PI()/180)/180))
    +(((%f-lat)*PI()*12656/180)*((%f-lat)*PI()*12656/180))
    )<%d limit 20";
        $list=M()->query($sql,array($lng,$lat,$lng,$lat,$lat,$lat,$scope));
        $data=array('err_code'=>200,'err_msg'=>$list);
        $this->ajaxReturn($data,'JSON');
    }
}